package com.module_live.view;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.bumptech.glide.Glide;
import com.lib.app.CodeUtil;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.ui.activity.web.base.BaseBusinessWebActivity;
import com.lib.utls.glide.GlideConfig;
import com.lib.utls.upload.QiNiuUploadTask;
import com.lib.utls.upload.initerface.FileUploadListener;
import com.luck.picture.lib.photoview.PhotoView;
import com.luck.picture.lib.tools.ToastManage;
import com.module_live.R;
import com.module_live.activity.CoachStudyLivingActivity;
import com.module_live.bean.coachstudy.UploadHomeWorkImgBean;
import com.zyyoona7.popup.EasyPopup;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import me.kareluo.imaging.IMGTextEditDialog;
import me.kareluo.imaging.core.IMGMode;
import me.kareluo.imaging.core.IMGText;
import me.kareluo.imaging.view.IMGColorGroup;
import me.kareluo.imaging.view.IMGView;
import okhttp3.internal.Util;


public class ZoomImagePopupUtils implements View.OnClickListener,
        IMGTextEditDialog.Callback, RadioGroup.OnCheckedChangeListener,
        DialogInterface.OnShowListener, DialogInterface.OnDismissListener, PopupWindow.OnDismissListener {


    private Activity activity;

    //背景图片显示以及底部操作按钮组
    protected IMGView mImgView;
    private RadioGroup mModeGroup;

    //颜色选择组
    private IMGColorGroup mColorGroup;

    private IMGTextEditDialog mTextDialog;

    //颜色与撤销整体容器
    private View mLayoutOpSub;

    //底部颜色选择容器
    private ViewSwitcher mOpSwitcher, mOpSubSwitcher;

    public static final int OP_HIDE = -1;

    public static final int OP_CLIP = 1;

    public static final int OP_SUB_DOODLE = 0;

    public static final String EXTRA_IMAGE_URI = "IMAGE_URI";

    public static final String EXTRA_IMAGE_SAVE_PATH = "IMAGE_SAVE_PATH";

    public ZoomImagePopupUtils(Activity ac) {

        this.activity = ac;

        initZoomImagePop();
    }

    private EasyPopup zoomPop;

    private void initZoomImagePop() {
        zoomPop = EasyPopup.create()
                .setContext(activity)
                .setContentView(R.layout.popup_zoom_image_1)
                .setWidth(WindowManager.LayoutParams.FILL_PARENT)
                .setHeight(WindowManager.LayoutParams.FILL_PARENT)
                .setOnViewListener(new EasyPopup.OnViewListener() {
                    @Override
                    public void initViews(View view, EasyPopup basePopup) {

                        initZoomImageView(view);
                        initIVListener(basePopup);

//                        initDoodleView();

                    }

                })
                .setFocusAndOutsideEnable(true)
                .apply();

    }

    private void initDoodleView() {

    }

    RadioButton rb_doodle;
    ImageButton btn_text, btn_undo, btn_rotate;
    TextView tvCancel, tvSure;

    private void initZoomImageView(View view) {

//        iv_photo = view.findViewById(R.id.iv_photo);

//        iv_quit = view.findViewById(R.id.iv_quit);
//        iv_pen = view.findViewById(R.id.iv_pen);
//        iv_text = view.findViewById(R.id.iv_text);
//        iv_cancel = view.findViewById(R.id.iv_cancel);
//        iv_sure = view.findViewById(R.id.iv_sure);

        //背景图片显示以及底部操作按钮
        mImgView = view.findViewById(R.id.image_canvas);
        mModeGroup = view.findViewById(R.id.rg_modes);

        //底部颜色选择容器
        mOpSwitcher = view.findViewById(R.id.vs_op);
        mOpSubSwitcher = view.findViewById(R.id.vs_op_sub);

        //颜色选择组
        mColorGroup = view.findViewById(R.id.cg_colors);
        mColorGroup.setOnCheckedChangeListener(this);

        //颜色与撤销整体容器
        mLayoutOpSub = view.findViewById(R.id.layout_op_sub);

        rb_doodle = view.findViewById(R.id.rb_doodle);
        btn_text = view.findViewById(R.id.btn_text);
        tvCancel = view.findViewById(R.id.tv_cancel);
        tvSure = view.findViewById(R.id.tv_done);
        btn_undo = view.findViewById(R.id.btn_undo);
        btn_rotate = view.findViewById(R.id.btn_rotate);
    }

    private void initIVListener(EasyPopup basePopup) {

//        iv_quit.setOnClickListener(this);
//        iv_pen.setOnClickListener(this);
//        iv_text.setOnClickListener(this);
//        iv_cancel.setOnClickListener(this);
//        iv_sure.setOnClickListener(this);

        rb_doodle.setOnClickListener(this);
        btn_text.setOnClickListener(this);
        tvCancel.setOnClickListener(this);
        tvSure.setOnClickListener(this);
        btn_undo.setOnClickListener(this);
        btn_rotate.setOnClickListener(this);

        basePopup.setOnDismissListener(this);
    }


    public void showAnswerPopuPopu(View view) {
        zoomPop.showAtLocation(view, Gravity.CENTER, 0, 0);
    }


    public interface ZoomImagePopupUtilsListener {

        //图片批改成功
        void onImageDealedSuccess(String imgLoaclPath, String imgUrl);
    }

    /**
     * interface
     */
    private ZoomImagePopupUtilsListener listener;

    public void setZoomImagePopupUtilsListener(ZoomImagePopupUtilsListener zoomImagePopupUtilsListener) {

        this.listener = zoomImagePopupUtilsListener;

    }

    @Override
    public void onDismiss() {

//        LogUtil.e("operbitmap-----------onDismiss");
//        if (operbitmap != null && !operbitmap.isRecycled()) {
//            LogUtil.e("isRecycled-----------null");
//            operbitmap = null;
//        }
//        operbitmap.recycle();
//        operbitmap = null;
    }


    public void dismiss() {
//        if (operbitmap != null && !operbitmap.isRecycled()) {
//            operbitmap = null;
//        }
//        operbitmap.recycle();
//        operbitmap = null;
        zoomPop.dismiss();
    }

//    Bitmap operbitmap = null;

    public int studentId;

    public void setZoomImage(String type, String url) {
//        Glide.with(activity)
//                .load(url)
//                .apply(GlideConfig.getRectangleOptions())
//                .into(mImgView);
        if (StringUtil.isNotEmpty(url, true) && url.length() > 10) {
            new ImageTask().execute(url);
        }
        if (StringUtil.isNotEmpty(type, true)) {
            if ("StudentFinsihedWork".equals(type)) {
                mOpSwitcher.setVisibility(View.VISIBLE);
            } else {
                mOpSwitcher.setVisibility(View.GONE);
            }
        }
    }

    public void setZoomImage(String type, String url, int studentId) {
//        Glide.with(activity)
//                .load(url)
//                .apply(GlideConfig.getRectangleOptions())
//                .into(mImgView);
        if (studentId > 0) {
            this.studentId = studentId;
        }

        if (StringUtil.isNotEmpty(url, true) && url.length() > 10) {
            new ImageTask().execute(url);
        }

        if (StringUtil.isNotEmpty(type, true)) {
            if ("StudentFinsihedWork".equals(type)) {
                mOpSwitcher.setVisibility(View.VISIBLE);
            } else {
                mOpSwitcher.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onClick(View v) {
//        int i = v.getId();
//        if (R.id.iv_quit == i) {
//
//            zoomPop.dismiss();
//        } else if (R.id.iv_pen == i) {
//
//        } else if (R.id.iv_text == i) {
//
//        } else if (R.id.iv_cancel == i) {
//
//        } else if (R.id.iv_sure == i) {
//
//        }
        int vid = v.getId();
        if (vid == R.id.rb_doodle) {
            mImgView.setMode(IMGMode.DOODLE);
            updateModeUI();

        } else if (vid == R.id.btn_text) {

            onTextModeClick();
        } else if (vid == R.id.btn_undo) {
            mImgView.undoDoodle();

        } else if (vid == R.id.tv_done) {
            onDoneClick();

        } else if (vid == R.id.tv_cancel) {

            dismiss();
        } else if (vid == R.id.btn_rotate) {
            mImgView.doRotate();
        }

    }

    @Override
    public void onText(IMGText text) {
        mImgView.addStickerText(text);
    }


    @Override
    public void onDismiss(DialogInterface dialog) {
        mOpSwitcher.setVisibility(View.VISIBLE);
    }

    @Override
    public void onShow(DialogInterface dialog) {
        mOpSwitcher.setVisibility(View.GONE);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        mImgView.setPenColor(mColorGroup.getCheckColor());
    }

    public void onDoneClick() {
        // TODO: 2020/10/10 0010  保存图片
        Bitmap bitmap = mImgView.saveBitmap();
        String imgLoacalUrl = saveToBitmapToLocal(bitmap);

        //获取图片路径,上传到服务器
        if (StringUtil.isNotEmpty(imgLoacalUrl, true)) {
            LogUtil.e("批改之后的图片本地保存地址为：" + imgLoacalUrl);

//            upLoadImage(imgLoacalUrl);
            if (listener != null) {
                listener.onImageDealedSuccess(imgLoacalUrl, imgLoacalUrl);
            }

            dismiss();
        }

    }

    public void onTextModeClick() {
        if (mTextDialog == null) {
            mTextDialog = new IMGTextEditDialog(activity, this);
            mTextDialog.setOnShowListener(this);
            mTextDialog.setOnDismissListener(this);
        }
        mTextDialog.show();
    }

    public void updateModeUI() {
        IMGMode mode = mImgView.getMode();
        switch (mode) {
            case DOODLE:
                mModeGroup.check(R.id.rb_doodle);
                setOpSubDisplay(OP_SUB_DOODLE);
                break;
            case NONE:
                mModeGroup.clearCheck();
                setOpSubDisplay(OP_HIDE);
                break;
        }
    }

    public void setOpSubDisplay(int opSub) {
        if (opSub < 0) {
            mLayoutOpSub.setVisibility(View.GONE);
        } else {
            mOpSubSwitcher.setDisplayedChild(opSub);
            mLayoutOpSub.setVisibility(View.VISIBLE);
        }
    }

    class ImageTask extends AsyncTask<String, Void, Bitmap> {

        protected Bitmap doInBackground(String... strings) {
            URL imageUrl = null;
            Bitmap bitmap = null;
            InputStream inputStream = null;
            try {
                imageUrl = new URL(strings[0]);
                HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                inputStream = conn.getInputStream();
                bitmap = BitmapFactory.decodeStream(inputStream);
                inputStream.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
//                operbitmap = bitmap;
                mImgView.setImageBitmap(bitmap);
            }
        }
    }

    private String saveToBitmapToLocal(Bitmap bitmap) {

        File doodleFile = null;
        File file = null;
        String savePath = Environment.getExternalStorageDirectory() + "/xstablet/teaoperimage/";
        if (TextUtils.isEmpty(savePath)) {
            File dcimFile = new File(Environment.getExternalStorageDirectory(), "xstablet");
            doodleFile = new File(dcimFile, "teaoperimage");
            //　保存的路径
            file = new File(doodleFile, System.currentTimeMillis() + ".jpg");
        } else {
            doodleFile = new File(savePath);
            //　保存的路径
            file = new File(doodleFile, System.currentTimeMillis() + ".jpg");
        }
        doodleFile.mkdirs();

        FileOutputStream outputStream = null;
        String url = "";
        try {
            outputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 95, outputStream);

            url = file.getAbsolutePath();

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            Util.closeQuietly(outputStream);
        }
        return url;
    }


}
